package com.mk.admin.service.impl;

import com.mk.admin.mapper.PatAddressMapper;
import com.mk.admin.model.ResultDto;
import com.mk.admin.model.dto.PatAddressDto;
import com.mk.admin.model.entity.PatAddressEntity;
import com.mk.admin.model.vo.PatAddressVo;
import com.mk.admin.service.PatAddressService;
import com.mk.admin.util.DateTool;
import com.mk.admin.util.JSONCopy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PatAddressServiceImpl implements PatAddressService {
    @Autowired
    private PatAddressMapper patAddressMapper;

    @Override
    public ResultDto select(PatAddressVo patAddressVo) {
        PatAddressEntity entity = JSONCopy.copy(patAddressVo, PatAddressEntity.class);
        return ResultDto.data(patAddressMapper.count(entity), patAddressMapper.select(entity));
    }

    @Override
    public ResultDto add(PatAddressVo patAddressVo) {
        patAddressVo.setCreateTime(DateTool.format());
        return ResultDto.data(patAddressMapper.insert(setOtherStatus(patAddressVo)));
    }

    @Override
    public ResultDto update(PatAddressVo patAddressVo) {
        patAddressVo.setUpdateTime(DateTool.format());
        return ResultDto.data(patAddressMapper.updateById(setOtherStatus(patAddressVo)));
    }

    /**
     * 设置其他地址的默认地址为0
     *
     * @param patAddressVo
     */
    private PatAddressEntity setOtherStatus(PatAddressVo patAddressVo) {
        PatAddressEntity entity = new PatAddressEntity();
        if (patAddressVo.getStatus() == 1) {
//           如果传递过来的是默认地址，则需要将以前的默认修改为0
            entity.setPatId(patAddressVo.getPatId());
            List<PatAddressDto> list = patAddressMapper.select(entity);
            for (PatAddressDto patAddressDto : list) {
                if (patAddressDto.getStatus() == 1) {
                    patAddressMapper.status(patAddressDto.getId());
                }
            }
        }
        entity = JSONCopy.copy(patAddressVo, PatAddressEntity.class);
        return entity;
    }

    @Override
    public ResultDto delete(int id) {
        return ResultDto.data(patAddressMapper.deleteById(id));
    }

    @Override
    public ResultDto status(int id) {
        List<PatAddressDto> list = patAddressMapper.select(null);
        for (PatAddressDto patAddressDto : list) {
            if (patAddressDto.getStatus() == 1) {
                patAddressMapper.status(patAddressDto.getId());
            }
        }
        return ResultDto.data(patAddressMapper.status(id));
    }
}
